import { asyncRoutes, routes } from '@/router'
import Cookies from 'js-cookie'
export default{
    state: {
        isCollapse:false,
        tabList:[],
        menu:[],
        role: null,
        count:0,
    },
    mutations: {
        collapseMenu(state){
            state.isCollapse = !state.isCollapse
        },
        selectMenu(state,val){
            if(val.name !== 'home'){
                const index = state.tabList.findIndex(item => item.path === val.path)
                if(index === -1){
                    state.tabList.push(val)
                }
            }
        },
        closeTag(state,item){
            const index = state.tabList.findIndex(val => val.path === item.path)
            state.tabList.splice(index,1)
        },

        generateRoutes(state, role) {
            if(state.count == 1)
                return
            if (role != "") {
                state.role = role
                var arr = []
                asyncRoutes.forEach((item) => {
                    if (item.hasOwnProperty('roles')) {
                        if (item.roles.includes(role)) {
                            arr.push(item)
                        }
                    }
                })
                
            }
            var accessedRoutes = arr || []
            routes.forEach((item, index) => {
                if (item.name.includes('Main')) {
                    state.menu = routes[index].children.concat(accessedRoutes)
                    Cookies.set('menu',JSON.stringify(state.menu))
                }
            })
        },
        addMenu(state,router){
            if(state.count == 1 || Cookies.get('menu') == undefined){
                return
            }
            const menu = JSON.parse(Cookies.get('menu'))
            state.menu = menu
            const menuArray = []
            menu.forEach(item => {
                if(item.children){
                    item.children.map(item => {
                        item.component = () => import(`../views/HousekeepingPlatform${item.name}.vue`)
                        return item
                    })
                    menuArray.push(...item.children)
                }else{
                    item.component = () => import(`../views/HousekeepingPlatform/${item.name}.vue`)
                    menuArray.push(item)
                }
            })
            menuArray.forEach(item =>{
                router.addRoute("Main",item)
            })
            state.count = 1
        }
    }
}